package com.example.smartwaterapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.smartwaterapi.common.api.ErrorCode;
import com.example.smartwaterapi.common.exception.BusinessException;
import com.example.smartwaterapi.entity.User;
import com.example.smartwaterapi.entity.UserWatchface;
import com.example.smartwaterapi.entity.Watchface;
import com.example.smartwaterapi.mapper.UserWatchfaceMapper;
import com.example.smartwaterapi.mapper.WatchfaceMapper;
import com.example.smartwaterapi.service.UserService;
import com.example.smartwaterapi.service.WatchfaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 表盘服务实现类
 */
@Slf4j
@Service
public class WatchfaceServiceImpl extends ServiceImpl<WatchfaceMapper, Watchface> implements WatchfaceService {

    @Autowired
    private UserWatchfaceMapper userWatchfaceMapper;

    @Autowired
    private UserService userService;

    /**
     * 分页获取表盘列表
     */
    @Override
    @Cacheable(value = "watchface", key = "'list:' + #page + ':' + #size + ':' + #params", unless = "#result == null")
    public Page<Watchface> getWatchfaceList(Integer page, Integer size, Map<String, Object> params) {
        Page<Watchface> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Watchface> wrapper = new LambdaQueryWrapper<>();
        
        // 状态为上架
        wrapper.eq(Watchface::getStatus, 1);
        
        // 分类过滤
        if (params != null && params.containsKey("category") && StringUtils.hasText(params.get("category").toString())) {
            wrapper.eq(Watchface::getCategory, params.get("category"));
        }
        
        // 类型过滤
        if (params != null && params.containsKey("type") && params.get("type") != null) {
            wrapper.eq(Watchface::getType, params.get("type"));
        }
        
        // 价格类型过滤
        if (params != null && params.containsKey("priceType") && params.get("priceType") != null) {
            wrapper.eq(Watchface::getPriceType, params.get("priceType"));
        }
        
        // 关键字搜索
        if (params != null && params.containsKey("keyword") && StringUtils.hasText(params.get("keyword").toString())) {
            String keyword = params.get("keyword").toString();
            wrapper.like(Watchface::getName, keyword)
                   .or()
                   .like(Watchface::getDescription, keyword)
                   .or()
                   .like(Watchface::getTags, keyword);
        }
        
        // 排序
        if (params != null && params.containsKey("sortField") && params.containsKey("sortOrder")) {
            String sortField = params.get("sortField").toString();
            String sortOrder = params.get("sortOrder").toString();
            
            switch (sortField) {
                case "createTime":
                    if ("asc".equals(sortOrder)) {
                        wrapper.orderByAsc(Watchface::getCreatedAt);
                    } else {
                        wrapper.orderByDesc(Watchface::getCreatedAt);
                    }
                    break;
                case "downloadCount":
                    if ("asc".equals(sortOrder)) {
                        wrapper.orderByAsc(Watchface::getDownloadCount);
                    } else {
                        wrapper.orderByDesc(Watchface::getDownloadCount);
                    }
                    break;
                case "ratingAvg":
                    if ("asc".equals(sortOrder)) {
                        wrapper.orderByAsc(Watchface::getRatingAvg);
                    } else {
                        wrapper.orderByDesc(Watchface::getRatingAvg);
                    }
                    break;
                default:
                    wrapper.orderByDesc(Watchface::getIsFeatured).orderByDesc(Watchface::getSortOrder);
            }
        } else {
            // 默认排序：先推荐，再按排序值，最后按创建时间
            wrapper.orderByDesc(Watchface::getIsFeatured)
                   .orderByDesc(Watchface::getSortOrder)
                   .orderByDesc(Watchface::getCreatedAt);
        }
        
        return page(pageParam, wrapper);
    }

    /**
     * 获取表盘详情
     */
    @Override
    @Cacheable(value = "watchface", key = "'detail:' + #id", unless = "#result == null")
    public Watchface getWatchfaceDetail(Long id) {
        Watchface watchface = getById(id);
        if (watchface == null) {
            throw new BusinessException(ErrorCode.WATCHFACE_NOT_FOUND);
        }
        
        // 检查表盘状态
        if (watchface.getStatus() != 1) {
            throw new BusinessException(ErrorCode.WATCHFACE_NOT_FOUND, "表盘已下架");
        }
        
        return watchface;
    }

    /**
     * 获取推荐表盘
     */
    @Override
    @Cacheable(value = "watchface", key = "'featured:' + #limit", unless = "#result == null || #result.isEmpty()")
    public List<Watchface> getFeaturedWatchfaces(Integer limit) {
        LambdaQueryWrapper<Watchface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Watchface::getStatus, 1)
               .eq(Watchface::getIsFeatured, 1)
               .orderByDesc(Watchface::getSortOrder)
               .last("LIMIT " + limit);
        return list(wrapper);
    }

    /**
     * 获取热门表盘
     */
    @Override
    @Cacheable(value = "watchface", key = "'popular:' + #limit", unless = "#result == null || #result.isEmpty()")
    public List<Watchface> getPopularWatchfaces(Integer limit) {
        // 使用自定义SQL查询热门表盘
        return baseMapper.getPopularWatchfaces(limit);
    }

    /**
     * 用户下载表盘
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {"watchface", "userWatchface"}, allEntries = true)
    public UserWatchface downloadWatchface(Long userId, Long watchfaceId) {
        // 检查用户
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND);
        }
        
        // 检查表盘
        Watchface watchface = getWatchfaceDetail(watchfaceId);
        
        // 检查用户是否已下载过该表盘
        LambdaQueryWrapper<UserWatchface> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserWatchface::getUserId, userId)
                   .eq(UserWatchface::getWatchfaceId, watchfaceId);
        UserWatchface userWatchface = userWatchfaceMapper.selectOne(queryWrapper);
        
        if (userWatchface != null) {
            // 已下载过，更新下载次数
            userWatchface.setDownloadCount(userWatchface.getDownloadCount() + 1);
            userWatchface.setUpdatedAt(LocalDateTime.now());
            userWatchfaceMapper.updateById(userWatchface);
            
            // 更新表盘下载次数
            baseMapper.incrementDownloadCount(watchfaceId);
            
            return userWatchface;
        }
        
        // 检查表盘价格类型
        switch (watchface.getPriceType()) {
            case 0: // 免费
                userWatchface = createUserWatchface(userId, watchface, 2, BigDecimal.ZERO, 0);
                break;
                
            case 1: // 付费
                // 实际项目中应该有支付逻辑
                throw new BusinessException(ErrorCode.WATCHFACE_INSTALL_FAILED, "付费表盘需要先购买");
                
            case 2: // 会员专享
                if (!"basic".equals(user.getMembershipLevel())) {
                    // 检查会员等级
                    if (watchface.getMembershipRequired() != null && 
                        !watchface.getMembershipRequired().equals(user.getMembershipLevel())) {
                        throw new BusinessException(ErrorCode.WATCHFACE_INSTALL_FAILED, 
                            "需要" + watchface.getMembershipRequired() + "会员才能下载此表盘");
                    }
                    
                    userWatchface = createUserWatchface(userId, watchface, 3, BigDecimal.ZERO, 0);
                } else {
                    throw new BusinessException(ErrorCode.WATCHFACE_INSTALL_FAILED, "需要会员才能下载此表盘");
                }
                break;
                
            case 3: // 积分兑换
                Integer pointsRequired = watchface.getPointsRequired();
                if (user.getPoints() < pointsRequired) {
                    throw new BusinessException(ErrorCode.WATCHFACE_INSTALL_FAILED, "积分不足，需要" + pointsRequired + "积分");
                }
                
                // 扣除积分
                boolean updated = userService.updatePoints(userId, -pointsRequired);
                if (!updated) {
                    throw new BusinessException(ErrorCode.WATCHFACE_INSTALL_FAILED, "积分扣除失败");
                }
                
                userWatchface = createUserWatchface(userId, watchface, 4, BigDecimal.ZERO, pointsRequired);
                break;
                
            default:
                throw new BusinessException(ErrorCode.WATCHFACE_INSTALL_FAILED, "不支持的价格类型");
        }
        
        // 更新表盘下载次数
        baseMapper.incrementDownloadCount(watchfaceId);
        
        return userWatchface;
    }

    /**
     * 创建用户表盘记录
     */
    private UserWatchface createUserWatchface(Long userId, Watchface watchface, Integer acquireType, 
                                           BigDecimal pricePaid, Integer pointsUsed) {
        UserWatchface userWatchface = new UserWatchface();
        userWatchface.setUserId(userId);
        userWatchface.setWatchfaceId(watchface.getId());
        userWatchface.setAcquireType(acquireType);
        userWatchface.setPricePaid(pricePaid);
        userWatchface.setPointsUsed(pointsUsed);
        userWatchface.setDownloadCount(1);
        userWatchface.setInstallCount(0);
        userWatchface.setIsFavorite(0);
        userWatchface.setCreatedAt(LocalDateTime.now());
        userWatchface.setUpdatedAt(LocalDateTime.now());
        
        userWatchfaceMapper.insert(userWatchface);
        return userWatchface;
    }

    /**
     * 用户收藏/取消收藏表盘
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "userWatchface", allEntries = true)
    public boolean toggleFavorite(Long userId, Long watchfaceId, boolean favorite) {
        // 检查用户
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND);
        }
        
        // 检查表盘
        Watchface watchface = getById(watchfaceId);
        if (watchface == null) {
            throw new BusinessException(ErrorCode.WATCHFACE_NOT_FOUND);
        }
        
        // 检查用户是否已下载过该表盘
        LambdaQueryWrapper<UserWatchface> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserWatchface::getUserId, userId)
                   .eq(UserWatchface::getWatchfaceId, watchfaceId);
        UserWatchface userWatchface = userWatchfaceMapper.selectOne(queryWrapper);
        
        if (userWatchface == null) {
            throw new BusinessException(ErrorCode.WATCHFACE_NOT_FOUND, "请先下载该表盘");
        }
        
        // 更新收藏状态 - 使用LambdaUpdateWrapper方式以兼容测试
        LambdaUpdateWrapper<UserWatchface> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserWatchface::getUserId, userId)
                   .eq(UserWatchface::getWatchfaceId, watchfaceId)
                   .set(UserWatchface::getIsFavorite, favorite ? 1 : 0)
                   .set(UserWatchface::getUpdatedAt, LocalDateTime.now());
        
        return userWatchfaceMapper.update(null, updateWrapper) > 0;
    }

    /**
     * 获取用户表盘库
     */
    @Override
    @Cacheable(value = "userWatchface", key = "'list:' + #userId + ':' + #page + ':' + #size", unless = "#result == null")
    public Page<UserWatchface> getUserWatchfaces(Long userId, Integer page, Integer size) {
        // 检查用户
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND);
        }
        
        Page<UserWatchface> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<UserWatchface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserWatchface::getUserId, userId)
               .orderByDesc(UserWatchface::getUpdatedAt);
        
        return userWatchfaceMapper.selectPage(pageParam, wrapper);
    }

    /**
     * 获取用户收藏的表盘
     */
    @Override
    @Cacheable(value = "userWatchface", key = "'favorite:' + #userId + ':' + #page + ':' + #size", unless = "#result == null")
    public Page<UserWatchface> getUserFavoriteWatchfaces(Long userId, Integer page, Integer size) {
        // 检查用户
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND);
        }
        
        Page<UserWatchface> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<UserWatchface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserWatchface::getUserId, userId)
               .eq(UserWatchface::getIsFavorite, 1)
               .orderByDesc(UserWatchface::getUpdatedAt);
        
        return userWatchfaceMapper.selectPage(pageParam, wrapper);
    }
} 